﻿using AchieveBLL;
using AchieveDAL;
using AchieveCommon;
using AchieveEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Text;
using System.Data.SqlClient;
using AchieveManageWeb.Models;
namespace AchieveManageWeb.Controllers
{
    [AchieveManageWeb.App_Start.JudgmentLogin]
    public class FinancialController : Controller
    {

        public ActionResult Index()
        {
            AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "费用报销单")); //日志记录
            return View();
        }

           public ActionResult ExpenseEdit()
        {
            //AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "访问视图", "订单计划达成率")); //日志记录
            return View();
        }
        /// <summary>
        /// 获取费用报销单分录
        /// </summary>
        /// <returns></returns>
           public ActionResult getExpenseEntry() {
               string strWhere = "1=1";
               string sort = Request["sort"] == null ? "rowId" : Request["sort"];
               string order = Request["order"] == null ? "desc" : Request["order"];
               string claimId = Request["id"] == null ? "1" : Request["id"];
               if (claimId == "")
               {
                   return Content("{\"msg\":\"查询失败,未获取到报销单id.\",\"success\":false}");
               }
               strWhere += string.Format("and claimId='{0}'", claimId);
               //首先获取前台传递过来的参数
               int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
               int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

               string content = "";
               int totalCount;   //输出参数 
               string columns = @"
claimId,rowId,
dept,
amount,
remark,projectNo,projectName,feeType,feeName
";
               DataTable dt = AchieveCommon.SqlPagerHelper.GetPagerBySQL(SqlHelper.connStr, "tbExpenseClaimEntry", columns, sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
               string strJson = AchieveCommon.JsonHelper.ToJson(dt);
               content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
               return Content(content);           
           }


     /// <summary>
     /// 费用报销清单的查询处理
     /// </summary>
     /// <returns></returns>
     public ActionResult GetExpenseList()
     {
         string strWhere = "1=1 ";
         string sort = Request["sort"] == null ? "id" : Request["sort"];
         string order = Request["order"] == null ? "desc" : Request["order"];
         string period = Request["period"] == null ? "" : Request["period"];
         if (period != "")
         {
             strWhere += string.Format("and period='{0}' ", period);
         }
         string status = Request["status"] == null ? "" : Request["status"];
         if(status=="0" ||status=="1")
         {
             strWhere += string.Format("and status='{0}' ", status);
         }
         string remark = Request["remark"] == null ? "" : Request["remark"];
         if (remark != "")
         {
             strWhere += string.Format("and remark like '%{0}%' ", remark);
         }
         string claimBy = Request["claimBy"] == null ? "" : Request["claimBy"];
         if (claimBy != "")
         {
             strWhere += string.Format("and claimBy = '{0}' ", claimBy);
         }


        // string dept = Request["dept"] == null ? "0" : Request["dept"];
        // string projectNo = Request["projectNo"] == null ? "" : Request["projectNo"];
        // string view = Request["view"] == null ? "PMMaintain" : Request["view"];
         
         //首先获取前台传递过来的参数
         int pageindex = Request["page"] == null ? 1 : Convert.ToInt32(Request["page"]);//输出的数据页码
         int pagesize = Request["rows"] == null ? 10 : Convert.ToInt32(Request["rows"]);//每页输出数量

         string content = "";        
             int totalCount;   //输出参数 
             string columns = @"
id, 
total,
remark,
claimBy,claimDept,
claimTime,
period,status,
createBy,
createTime,
updateBy,
updateTime,
checkBy,
checkTime
";
             DataTable dt = AchieveCommon.SqlPagerHelper.GetPagerBySQL(SqlHelper.connStr, "tbExpenseClaim", columns, sort + " " + order, pagesize, pageindex, strWhere, out totalCount);
             string strJson = AchieveCommon.JsonHelper.ToJson(dt);
             content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
         return Content(content);
     }

/// <summary>
/// 新增费用报销单
/// </summary>
/// <returns></returns>
     public ActionResult AddNewExpense()
     {
         UserEntity uInfo = ViewData["Account"] as UserEntity;
         try
         {
            // string id = SqlHelper.GetSerialNumber("tbExpenseClaim", "id");
             string id = string.IsNullOrWhiteSpace(Request["claimId"]) ? "" : Request["claimId"];
             if (id=="")
             {
                return Content("{\"msg\":\"添加失败,未获取到claimId.\",\"success\":false}"); 
             }
             string claimDept = Request["claimDept"] == null ? "" : Request["claimDept"];
             //string feeType = Request["feeType"] == null ? "" : Request["feeType"];
             //decimal travelFee = string.IsNullOrWhiteSpace(Request["travelFee"]) ? 0 : Convert.ToDecimal(Request["travelFee"]);
             //decimal officeFee = string.IsNullOrWhiteSpace(Request["officeFee"]) ? 0 : Convert.ToDecimal(Request["officeFee"]);
             //decimal entertainmentFee = string.IsNullOrWhiteSpace(Request["entertainmentFee"]) ? 0 : Convert.ToDecimal(Request["entertainmentFee"]);
             //decimal deduct = string.IsNullOrWhiteSpace(Request["deduct"]) ? 0 : Convert.ToDecimal(Request["deduct"]);
             decimal total = string.IsNullOrWhiteSpace(Request["total"]) ? 0 : Convert.ToDecimal(Request["total"]);
             string claimTime = string.IsNullOrWhiteSpace(Request["claimTime"]) ? null : Request["claimTime"];
             string claimBy = Request["claimBy"] == null ? "" : Request["claimBy"];
             string period = Request["period"] == null ? "" : Request["period"];
             string remark = Request["remark"] == null ? "" : Request["remark"];
             string createTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
             string UpdateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss"); 
             string UpdateBy = uInfo.AccountName;
             string createBy = uInfo.AccountName; 

             string sql = @"
INSERT INTO [dbo].[tbExpenseClaim]
           ([id]  
           ,[total]
           ,[claimBy]
           ,[claimTime]
           ,[createBy]
           ,[createTime],remark,claimDept,period,status
          )
     VALUES
           ('{0}',{1},'{2}','{3}','{4}','{5}','{6}','{7}','{8}','0')";

             sql = string.Format(sql, id, total, claimBy, claimTime, createBy, createTime, remark, claimDept, period);
             if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr,sql)>0)
             {
                  return Content("{\"msg\":\"添加成功\",\"success\":true}");
             }
             else
             {
                 return Content("{\"msg\":\"添加失败.\",\"success\":false}");
             }

         }
         catch (Exception ex)
         {
             return Content("{\"msg\":\"添加失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
         }

     }
     /// <summary>
     /// 报销单分录处理函数接口，必须参数claimId，rowId，method：insert，delete，update
     /// </summary>
     /// <returns></returns>
     public ActionResult ExpenseClaimEntyHandle()
     {
         string claimId = Request["claimId"] == null ? "" : Request["claimId"];
         string rowId = Request["rowId"] == null ? "" : Request["rowId"];
         string method = Request["method"] == null ? "" : Request["method"];
         if (claimId==""||rowId==""||method=="")
         {
             return Content("{\"msg\":\"参数不全，处理失败.\",\"success\":false}");
         }
         string feeType = Request["feeType"] == null ? "" : Request["feeType"];
         string feeName = Request["feeName"] == null ? "" : Request["feeName"];
         string dept = Request["dept"] == null ? "" : Request["dept"];
         string projectNo = Request["projectNo2"] == null ? "" : Request["projectNo2"];//不用form中得value值
         string projectName = Request["projectName"] == null ? "" : Request["projectName"];
         string remark = Request["remark"] == null ? "" : Request["remark"];
         decimal amount = string.IsNullOrWhiteSpace(Request["amount"]) ? 0 : Convert.ToDecimal(Request["amount"]);
         string sql = "";
         switch (method)
         {
             case   "insert":
                 sql = @"insert into tbExpenseClaimEntry
(claimId,rowId,feeType,feeName,dept,projectNo,projectName,remark,amount)
values('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}',{8})";
                 sql = string.Format(sql, claimId, rowId, feeType, feeName, dept, projectNo, projectName, remark,amount);
                     break;
             case "update":
                 sql = @"update tbExpenseClaimEntry set feeType='{0}',feeName='{1}',remark='{2}',amount={3},
dept='{4}',projectNo='{5}',projectName='{6}' where claimId='{7}'and rowId='{8}'";
                 sql = string.Format(sql,  feeType, feeName,remark,amount, dept, projectNo, projectName, claimId, rowId);
                     break;
             case "delete":
                     sql = "delete tbExpenseClaimEntry where claimId='{0}'and rowId='{1}'";
                     sql = string.Format(sql, claimId, rowId);
                     break;
             default:
                 break;
         }
         if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr,sql)>0)
         {
             return Content("{\"msg\":\"操作成功\",\"success\":true}");
         }
         else
         {
             return Content("{\"msg\":\"处理失败.\",\"success\":false}");
         }
     }
     /// <summary>
     /// 根据projectid删除项目主表即节点子表，不处理附件！
     /// </summary>
     /// <returns></returns>
     public ActionResult DelExpenseByID()
     {
         UserEntity uInfo = ViewData["Account"] as UserEntity;
         try
         {
             string ExpenseID = Request["ID"] == null ? "" : Request["ID"];
             if (!string.IsNullOrEmpty(ExpenseID))
             {
                 string sql = "delete tbExpenseClaim where id = '{0}'";
                 sql = string.Format(sql, ExpenseID);
                 if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
                 {
                     AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "费用报销", "删除报销单" + ExpenseID)); //日志记录
                     return Content("{\"msg\":\"删除成功！\",\"success\":true}");
                 }
                 else
                 {
                     return Content("{\"msg\":\"删除失败！\",\"success\":false}");
                 }
             }
             else
             {
                 return Content("{\"msg\":\"删除失败！项目id为空\",\"success\":false}");
             }
         }
         catch (Exception ex)
         {
             return Content("{\"msg\":\"删除失败," + ex.Message + "\",\"success\":false}");
         }
     }
        /// <summary>
        /// 报销单审核
        /// </summary>
        /// <returns></returns>
     public ActionResult CheckExpenseByID()
     {
         UserEntity uInfo = ViewData["Account"] as UserEntity;
         try
         {
             string ExpenseID = Request["ID"] == null ? "" : Request["ID"];
             if (!string.IsNullOrEmpty(ExpenseID))
             {
                 string nowTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
                 string account = uInfo.AccountName;
                 string sql = "update tbExpenseClaim set status='1', checkBy='{0}', checkTime='{1}' where id = '{2}'";
                 sql = string.Format(sql,account,nowTime, ExpenseID);
                 if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
                 {
                     AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "费用报销", "审核报销单" + ExpenseID)); //日志记录
                     return Content("{\"msg\":\"审核成功！\",\"success\":true}");
                 }
                 else
                 {
                     return Content("{\"msg\":\"审核失败！\",\"success\":false}");
                 }
             }
             else
             {
                 return Content("{\"msg\":\"审核失败！项目id为空\",\"success\":false}");
             }
         }
         catch (Exception ex)
         {
             return Content("{\"msg\":\"审核失败," + ex.Message + "\",\"success\":false}");
         }
     }


     /// <summary>
     /// 报销单取消审核
     /// </summary>
     /// <returns></returns>
     public ActionResult UnCheckExpenseByID()
     {
         UserEntity uInfo = ViewData["Account"] as UserEntity;
         try
         {
             string ExpenseID = Request["ID"] == null ? "" : Request["ID"];
             if (!string.IsNullOrEmpty(ExpenseID))
             {
                 string sql = "update tbExpenseClaim set status='0' where id = '{0}'";
                 sql = string.Format(sql, ExpenseID);
                 if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
                 {
                     AchieveManageWeb.Models.ActionFilters.LoggerHelper.Notes(new LogContent(ViewData, "费用报销", "撤销审核报销单" + ExpenseID)); //日志记录
                     return Content("{\"msg\":\"撤销审核成功！\",\"success\":true}");
                 }
                 else
                 {
                     return Content("{\"msg\":\"撤销审核失败！\",\"success\":false}");
                 }
             }
             else
             {
                 return Content("{\"msg\":\"撤销审核失败！项目id为空\",\"success\":false}");
             }
         }
         catch (Exception ex)
         {
             return Content("{\"msg\":\"撤销审核失败," + ex.Message + "\",\"success\":false}");
         }
     }

     /// <summary>
     /// 编辑费用单据信息
     /// </summary>
     /// <returns></returns>
     public ActionResult updateExpense()
     {
         UserEntity uInfo = ViewData["Account"] as UserEntity;
         try
         {
             string ExpenseID = Request["ID"] == null ? "" : Request["ID"];
             if (string.IsNullOrEmpty(ExpenseID)) return Content("{\"msg\":\"添加失败,未获取到单据ID.\",\"success\":false}");

             //string orderNo = string.IsNullOrWhiteSpace(Request["orderNo"]) ? "Ex" + ExpenseID : Request["orderNo"];
             string dept = Request["claimDept"] == null ? "" : Request["claimDept"];
             string period = Request["period"] == null ? "" : Request["period"];
             decimal total = string.IsNullOrWhiteSpace(Request["total"]) ? 0 : Convert.ToDecimal(Request["total"]);
             //decimal total = travelFee + officeFee + deduct + entertainmentFee;
             string claimBy = Request["claimBy"] == null ? "" : Request["claimBy"];
             string remark = Request["claimRemark"] == null ? "" : Request["claimRemark"];
             string claimTime = string.IsNullOrWhiteSpace(Request["claimTime"]) ? null : Request["claimTime"];
            // string claimTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
             //string createTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
             string updateTime = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");             
             string updateBy = uInfo.AccountName;
             string sql = @"
update tbExpenseClaim 
SET claimTime = '{0}', claimDept = '{1}',total = {2}, remark = '{3}',claimBy = '{4}',updateBy = '{5}',updateTime = '{6}', period='{7}' 
WHERE id = '{8}'";

             sql = string.Format(sql, claimTime, dept, total, remark, claimBy, updateBy, updateTime, period,ExpenseID);
             if (SqlHelper.ExecuteNonQuerySql(SqlHelper.connStr, sql) > 0)
             {
                 return Content("{\"msg\":\"修改成功\",\"success\":true}");
             }
             else
             {
                 return Content("{\"msg\":\"修改失败.\",\"success\":false}");
             }

         }
         
         catch (Exception ex)
         {
             return Content("{\"msg\":\"更新失败," + ex.Message.Trim().Replace("\r", "").Replace("\n", "") + "\",\"success\":false}");
         }

     }
     public ActionResult getExpenseRpt() {
         string groupType = Request["grouptype"] == null ? "dept" : Request["grouptype"];//projectNo
          string status = Request["status"] == null ? "all" : Request["status"];//all，0，1
          string period = Request["period"] == null ? "all" : Request["period"];//“2020-01”
          string periodType = Request["periodType"] == null ? "claimTime" : Request["periodType"];//claimPeriod 

          DataTable dt = RptBLL.getfybxDt(groupType, status, period, periodType);
         int totalCount = dt.Rows.Count;
         string strJson = AchieveCommon.JsonHelper.ToJson(dt);
         string content = "{\"total\": " + totalCount.ToString() + ",\"rows\":" + strJson + "}";
         return Content(content);
     }

  


    }
}
